package com.ken.blog.controller.web;

import com.alibaba.fastjson.JSON;
import com.ken.blog.domain.Article;
import com.ken.blog.domain.Category;
import com.ken.blog.domain.ArticleRepository;
import com.ken.blog.domain.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @RequestMapping("/{id}")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
        ModelAndView mv = new ModelAndView("web/article/index");

        Article article = articleRepository.findOne(id);

        mv.addObject("article", article);


        //缓存测试
        boolean isExist = redisTemplate.hasKey("acticle_" + id);
        String jsonString = "";
        if (isExist) {
            System.out.println("存在缓存，直接读取");
            jsonString = stringRedisTemplate.opsForValue().get("acticle_" + id);
        } else {
            jsonString = JSON.toJSONString(article);
            System.out.println("不存在缓存，设置缓存");
            stringRedisTemplate.opsForValue().set("acticle_" + id, jsonString);
        }

//        stringRedisTemplate.opsForValue().set("testCache", "have a default test cache");
        System.out.println(jsonString);

        return mv;
    }
}
